function [template, predelay] = cb_template(funcid, samplerate, rise, decay, lpfilter, ntau)

global STACK
if(nargin < 6)
    ntau = 5;
end;

switch funcid
   case 1 % alpha function - decay is tau; rise and lpfilter are not used.
        predelay = decay;
        if(decay*ntau < 5)
            ntau = 5 / decay;
        end;
        N = floor((decay*ntau+predelay)/samplerate);
        for i = 1:N
            t = i*samplerate;
            if(t >= predelay)
                template(i) = ((t - predelay)/decay)*exp((-(t - predelay))/decay);
            else
                template(i) = 0;
            end;

        end;
        m = max(template);
        template = template/m; % normalized to size 1.
        
    case 2 % standard for EPSC detection
        predelay = 2;
        if(predelay <= 1) predelay = 1;
        end;
        if(decay*ntau < 5) % less than 5 msec is a problem though
            ntau = 5/decay;
        end;
        N = floor((decay*ntau+predelay)/samplerate);
        for i = 1:N
            t = i*samplerate;
            if(t >= predelay)
                template(i) = (1-exp(-(t-predelay)/rise))^2*exp(-(t-predelay)/decay);
            else
                template(i) = 0;
            end;
        end;
        if(lpfilter > 0)
            fsamp = 1000/samplerate; % get sampling frequency
            fco = lpfilter;		% cutoff frequency in Hz
            wco = fco/(fsamp/2); % wco of 1 is for half of the sample rate, so set it like this...
            if(wco < 1) % if wco is > 1 then this is not a filter!
                [b, a] = butter(8, wco);
                template = filter(b, a, template); % filter each trace...
            end;
        end;

        m=max(template);
        template = template/m; % normalize to size 1.

 
    case 3 % dual exponential function with power
        predelay = 0.25;
        N = floor((decay*ntau+predelay)/samplerate);
        for i = 1:N
            t = i*samplerate;
            if(t >= predelay)
                td = t-predelay;
                template(i) = ((1-exp((-td/rise)))^2) * exp(-td/decay);
            else
                template(i) = 0;
            end;
        end;
    case 4 % use data from average waveform somewhere
        % 5/13/2008.
        % aveargin/zoom, etc put the displayed data into the "stack" variable
        % this is then usable as a template. It is normalized first, and
        % sent to the routine. 
        predelay = 0.05;
        template = STACK{1}; % pull from the new "stack" variable. 
        template = template/max(template);
    case 5 % use the average of the prior analysis.
        predelay = 0.05;
        template = STACK{1};
        template = template/max(template);
        
    otherwise
        template = [];
        end;

%htfig = newfigure('mini_showtemplate', 'Mini Template');
%plot(template);
return;
